package com.lumeng.spring.common.utils;

import com.lumeng.spring.common.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @Description: 参数校验的util
 * @Author: liulili
 * @Date: 19:41 2019/12/6
 */
@Slf4j
@Component
public class Arguments {

    private static LocaleMessageSource localeMessageSource;

    public Arguments(LocaleMessageSource localeMessageSource) {
        Arguments.localeMessageSource = localeMessageSource;
    }


    /**
     * 检查表达式是否成立
     *
     * @param expression: true 放行，false 抛出异常
     * @param errMsgKey:  国际化key
     */
    public static void check(boolean expression, String errMsgKey) {
        if (!expression) {
            fail(errMsgKey);
        }
    }

    /**
     * @param expression: true 放行，false 抛出异常
     * @param errMsgKey: 国际化key
     */
    public static void check(boolean expression,String errMsgKey, Object... args) {
        if (!expression) {
            fail(errMsgKey, args);
        }
    }


    /**
     * 检查参数是否不为null
     */
    public static <T> void notNull(T reference, String errMsgKey) {
        if (reference == null) {
           fail(errMsgKey);
        }
    }

    /**
     * 检查参数是否不为null
     */
    public static <T> void notNull(T reference, String errMsgKey, Object... args) {
        if (reference == null) {
            fail(errMsgKey, args);
        }
    }

    /**
     * 错误信息不为空，直接返回错误提示
     */
    public static void errMsg(String errMsgKey) {
        if (StringUtils.isNotEmpty(errMsgKey)) {
            fail(errMsgKey);
        }
    }

    /**
     * 检查字符串是否不为空
     */
    public static void notEmpty(String str, String errMsgKey) {
        if (str == null || str.isEmpty()) {
            fail(errMsgKey);
        }
    }

    /**
     * 检查字符串是否不为空
     */
    public static void notEmpty(String str, String errMsgKey, Object... args) {
        if (str == null || str.isEmpty()) {
            fail(errMsgKey, args);
        }
    }

    private static void fail(String errMsgKey, Object... args) {
        String msg = localeMessageSource.getMessage(errMsgKey, args);
        if (StrTools.isEmpty(msg)){
            msg = errMsgKey;
        }
        throw new RRException(msg);
    }
}
